package ph.com.gs3.formalistics.services;

import ph.com.gs3.formalistics.global.interfaces.CallbackCommand;
import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.HttpCommunicator;
import ph.com.gs3.formalistics.services.broadcasters.Broadcaster;
import ph.com.gs3.formalistics.services.managers.DataSynchronizationManager;
import ph.com.gs3.formalistics.services.managers.DataSynchronizationManager.FullUpdateManagerEventsListener;
import ph.com.gs3.formalistics.services.managers.DataSynchronizationManager.SyncType;
import ph.com.gs3.formalistics.services.managers.SessionManager;
import ph.com.gs3.formalistics.services.managers.SessionManager.CheckConnectionResult;
import ph.com.gs3.formalistics.services.synchronizers.DocumentsSynchronizer.DocumentsSynchronizerEventListener;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;

public class DataSynchronizationService extends IntentService {

	public static final String TAG = DataSynchronizationService.class.getSimpleName();
	public static final String NAME = DataSynchronizationService.class.getName();

	public static final String EXTRA_SYNC_TYPE = "sync_type";

	protected final SessionManager sessionMan = SessionManager.getApplicationInstance();

	private DataSynchronizationManager fullUpdateManager;
	private Broadcaster broadcaster;

	private static boolean fullUpdateOngoing;

	public DataSynchronizationService() {
		super(NAME);

		fullUpdateOngoing = false;
		fullUpdateManager = DataSynchronizationManager.getApplicationInstance();
		fullUpdateManager.setDocumentsSynchronizerEventListener(documentsSynchronizerEventListener);

		// sessionMan.addListener(sessionEventListener);
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		Bundle extras = intent.getExtras();

		final SyncType syncType;
		if (extras != null && extras.containsKey(EXTRA_SYNC_TYPE)) {
			syncType = (SyncType) extras.get(EXTRA_SYNC_TYPE);
		} else {
			syncType = SyncType.FULL_SYNC;
		}

		broadcaster = new Broadcaster(this);

		// Check session, then start synchronizing if session is available
		// sessionMan.addListener(sessionEventListener);
		sessionMan.checkConnectionToServer(
		        new CallbackCommand<SessionManager.CheckConnectionResult>() {

			        @Override
			        public void execute(CheckConnectionResult result) {

				        if (result.connectionStatus == HttpCommunicator.STATUS_CONNECTED) {
					        startUpdateService(syncType);
				        } else {
					        broadcaster
					                .broadcastFullUpdateNotStarted("Full update service not started, disconnected to server.");
				        }

			        }
		        }, null);
	}

	private void startUpdateService(SyncType syncType) {
		if (!fullUpdateOngoing) {
			fullUpdateOngoing = true;
			fullUpdateManager.setEventsListener(eventsListener);
			fullUpdateManager.startFullUpdate(syncType);
			fullUpdateOngoing = false;
		} else {
			FLLogger.d(TAG, "Full update manager is still busy.");
		}
	}

	// ===============================================================================
	// {{ Event Listeners

	private FullUpdateManagerEventsListener eventsListener = new FullUpdateManagerEventsListener() {

		@Override
		public void onReauthenticationNeeded() {
			sessionMan.logout();
			broadcaster.broadcast(Broadcaster.REAUTHENTICATION_REQUIRED);
			broadcaster.broadcast(Broadcaster.FULL_UPDATE_DONE);
		}

		@Override
		public void onFullUpdateDone() {
			broadcaster.broadcast(Broadcaster.FULL_UPDATE_DONE);
		}

		@Override
		public void onFormsSynchronized() {
			broadcaster.broadcast(Broadcaster.FORMS_SYNCHRONIZED);
		}

		@Override
		public void onOutgoingActionsSent() {
			broadcaster.broadcast(Broadcaster.OUGTOING_ACTIONS_SUBMITTED);
		}

		@Override
		public void onDocumentsSychronized() {
			broadcaster.broadcast(Broadcaster.DOCUMENTS_SYNCHRONIZED);
		}

	};

	private DocumentsSynchronizerEventListener documentsSynchronizerEventListener = new DocumentsSynchronizerEventListener() {

		@Override
		public void onNewDocumentsDownloaded() {
			broadcaster.broadcast(Broadcaster.DOCUMENTS_PARTIALLY_SYNCHRONIZED);
		}

		@Override
		public void onAllFormsDownloaded() {
			broadcaster.broadcast(Broadcaster.DOCUMENTS_SYNCHRONIZED);
		}
	};

	// protected SessionManagerEventListener sessionEventListener = new
	// SessionManagerEventListener() {
	//
	// @Override
	// public void onSessionLost() {
	// FLLogger.d(TAG, "Session lost");
	//
	// ServiceEventNotifierUtility.getDefaultInstance().dismissPrimaryNotification(
	// FullUpdateService.this);
	//
	// // sessionMan.removeListener(this);
	// sessionMan.logout();
	// broadcaster.broadcastReauthenticationRequired();
	// broadcaster.broadcastFullUpdateDone();
	//
	// }
	//
	// @Override
	// public void onModeChanged(Mode mode) {
	//
	// FLLogger.d(TAG, "mode change");
	//
	// if (mode == Mode.ONLINE) {
	// startUpdateService();
	// }
	//
	// ServiceEventNotifierUtility.getDefaultInstance().dismissPrimaryNotification(
	// FullUpdateService.this);
	//
	// }
	// };

}
